package com.tianyang.yukuaifu.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;

import com.tianyang.yukuaifu.common.interfaces.CommonConfig;
import com.tianyang.yukuaifu.module.luban.Luban;
import com.tianyang.yukuaifu.module.luban.OnRenameListener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.os.Environment.getExternalStorageDirectory;

/**
 * Description：File工具类
 * Created by 薛勇军 on 2018/7/26.
 */

public class FileUtil {

    /**
     * luban图片压缩
     *
     * @param filePath 图片地址
     * @param reName   重命名
     * @return
     */
    public static List<File> luban(Context context, String filePath, final String reName) {
        try {
            // 同步方法直接返回压缩后的文件
            return Luban.with(context)
                    .load(filePath)
                    .ignoreBy(CommonConfig.LUBAN_COMPRESSSIZE)
                    .isNeedDesired(true)
                    .desiredValue(CommonConfig.LUBAN_COMPRESSSIZE)
                    .setRenameListener(new OnRenameListener() {
                        @Override
                        public String rename(String filePath) {
                            return reName + "_" + System.currentTimeMillis();
                        }
                    })
                    .get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建目录
     *
     * @param dir
     */
    public static String mkdir(String dir) {
        String[] dirs = dir.split("/");
        String path = "";
        for (int i = 0; i < dirs.length; i++) {
            path = path + "/" + dirs[i];
            File appDir = new File(getExternalStorageDirectory(), path);
            if (!appDir.exists()) {
                boolean md = appDir.mkdirs();
            }
        }
        return getExternalStorageDirectory() + "/" + path;
    }

    /**
     * 保存图片二维码
     */
    public static File saveImage(Bitmap bmp) {
        if (bmp == null) return null;
        String path = mkdir("ykf/qrcode");
        File appDir = new File(path);
        String fileName = "qrcode_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file;
    }

    public static File saveImageToGallery(Context context, Bitmap bmp) {
        if (bmp == null) return null;
        String path = mkdir("ykf/付款二维码");
        File appDir = new File(path);
        String fileName = "qrcode_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
        return file;
    }

    public static File saveShareImageToGallery(Context context, Bitmap bmp) {
        if (bmp == null) return null;
        String path = mkdir("ykf/分享二维码");
        File appDir = new File(path);
        String fileName = "share_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

//        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
        return file;
    }

    public static boolean fileIsExists(String path) {
        if (path == null || path.trim().length() <= 0) {
            return false;
        }
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        Log.e("TMG", path + "file not exists");
        return true;
    }

    //图片保存到本地，--返回图片的路径
    public static String saveImg(ByteArrayOutputStream bos, String fileName) {
        String path = mkdir(CommonConfig.DIR_APP_CACHE);
        File appDir = new File(path);
        String fileNames = fileName + "_" + System.currentTimeMillis() + ".jpg";
        FileOutputStream fos = null;
        File file = new File(appDir, fileNames);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            fos.write(bos.toByteArray());
            fos.flush();
        } catch (IOException e) {
            path = "";
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (bos != null)
                    bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return path + "/" + fileNames;
    }

    // 这里是根据质量压缩.可以吧图片压缩到100K以下,然后保存到本地文件
    public static String compressAndSave(Bitmap image, String fileName) {
        ByteArrayOutputStream baos = null;
        String filePath = "";
        try {
            baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int options = 100;
            System.out.println(baos.toByteArray().length + "");
            while (baos.toByteArray().length / 1024 > 400) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                baos.reset();// 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;// 每次都减少10
            }
            // 在这里已经压缩到100以下了，但是只要调用了decodeStream就又会涨到200K,所以在操作之前把图片先保存到本地
            // 如果需要返回一个bitmap对象，则调用如下方法
            // ByteArrayInputStream isBm = new
            // ByteArrayInputStream(baos.toByteArray());
            // 把压缩后的数据baos存放到ByteArrayInputStream中
            // Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
            // 把ByteArrayInputStream数据生成图片
            filePath = saveImg(baos, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                image.recycle();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }

    /**
     * 删除缓存图片
     */
    public static void deleteCache() {
        //flie：要删除的文件夹的所在位置
        deleteFile(new File(CommonConfig.DIR_APP_CACHE));
    }

    /**
     * 删除文件夹下所有文件
     */
    public static  void deleteFile(File file) {
        try {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    File f = files[i];
                    deleteFile(f);
                }
                file.delete();//如要保留文件夹，只删除文件，请注释这行
            } else if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static File saveFileToBitmap(Bitmap mBitmap, String filePath, String fileName)  {
        File newFile = null;
        FileOutputStream fOut = null;
        try {
            File listnames = new File(filePath );
            if( !listnames.exists())
                listnames.mkdirs();
            newFile = new File(filePath + File.separator + fileName);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            fOut = new FileOutputStream(newFile);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOut != null) {
                    fOut.flush();
                    fOut.close();
                }
                mBitmap.recycle();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return newFile;
    }

    public static File saveFileToBitmap(Context context, Bitmap mBitmap, String filePath, String fileName)  {
        File newFile = null;
        FileOutputStream fOut = null;
        try {
            File listnames = new File(filePath );
            if( !listnames.exists())
                listnames.mkdirs();
            newFile = new File(filePath + File.separator + fileName);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            fOut = new FileOutputStream(newFile);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOut != null) {
                    fOut.flush();
                    fOut.close();
                }
                mBitmap.recycle();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + newFile.getPath())));
        return newFile;
    }

    /**
     * 从sd卡获取图片资源
     * @return
     */
    public static List<String> getImagePathFromSD(String filePath) {
        // 图片列表
        List<String> imagePathList = new ArrayList<String>();
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        if (!fileAll.exists()) {
            return imagePathList;
        }
        File[] files = fileAll.listFiles();
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsImageFile(file.getPath())) {
                imagePathList.add(file.getPath());
            }
        }
        // 返回得到的图片列表
        return imagePathList;
    }

    /**
     * 检查扩展名，得到图片格式的文件
     * @param fName  文件名
     * @return
     */
    @SuppressLint("DefaultLocale")
    private static boolean checkIsImageFile(String fName) {
        boolean isImageFile = false;
        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
                || FileEnd.equals("jpeg")|| FileEnd.equals("bmp") ) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }

    /**
     * 删除目录下所有的图片，限一级目录
     */
    public static void deleteImgFiles(String filtPath) {
        File root = new File(filtPath);
        if (!root.exists()) {
            return;
        }
        File files[] = root.listFiles();
        if (files != null) {
            for (File f : files) {
                if (checkIsImageFile(f.getPath())) {
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                }
            }
        }
        try {
            root.delete();
        } catch (Exception e) {

        }

    }
}
